// pages/productEdit/productEdit.js
const util = require('../../utils/util')
import * as API_Classify from '../../api/storeClassify'
import * as API_Upload from '../../utils/fileUpload'
import * as API_Product from '../../api/product'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isCopy:'',
    title:'修改商品',
    useStartTime:util.getDate(),
    useEndTime:util.getDate(),
    hotStateIndex:1,
    fixedTimeStateIndex:1,
    newUserStateIndex:1,
    appoinUnitIndex:0,
    YNArray: [
      {
        key: 'Y',
        value: '是'
      },
      {
        key: 'N',
        value: '否'
      }
    ],
    unitArray: [
      {
        value: '小时'
      },
      {
        value: '天'
      }
    ],
    //团单
    storeProduct:{
      storeId:null,
      productName:'',//团单名称
      classifyId:null,//团单分类
      productImage:'',//团单主图
      itemDetail:'',//团单
      infoId:null,//图文详情Id
      price:'',//团购价格
      storePrice:'',//门店价格
      fictiNum:'',//虚拟销量
      writeOffNum: '',//核销次数
      // hotState:'N',//是否热卖
      vipPrice: '',//会员售价
      fixedTimeState:'N',//是否是否固定有效期
      validDay:'',//有效期天数
      useStartTime:util.getDate(),
      useEndTime:util.getDate(),
      appoinNum: 1,//提前多久预约
      appoinUnit:'小时',
      couponsMaxNewUse:0,//商家新人最大优惠
      couponsMaxAll:0,//商家
      peopleNum:1,//适用人数
      peopleRight:'',//适用人群
      service:'',//商家服务
      isVip: 'Y' //是否会员售价
      // newUserState:'N'
    },
    //类型列表
    classifyList:[],
    //类型索引
    classifyIndex:0,
    // 提交状态
    showCommit:true,
    vipArr: [
      {value: 'Y', name: '是'},
      {value: 'N', name: '否'}
    ],
    timeArr: [
      {value: 'Y', name: '是'},
      {value: 'N', name: '否'}
    ],
    categoryLeft: 0,
    categoryshow: false,
    categoryRight: [],
    categoryResultId: 0, //商品分类选择id
    categoryName: '', //分类名
  },
  //分类左侧点击
  handleCategoryLeftClk(e) {
    const index = e.currentTarget.dataset.index
    const targetArr = this.data.classifyList[index]
    this.setData({
      categoryLeft: index,
      categoryRight: targetArr['children'] ? targetArr['children'] : [],
    })
  },
  //关闭分类选择
  handleCloseCategory() {
    this.setData({
      categoryshow:false
    })
  },
  //展示分类选择
  showCategory() {
    this.setData({
      categoryshow:true
    })
  },
  handleCategorySonClk(e) {
    const id = e.currentTarget.dataset.id
    const name = e.currentTarget.dataset.name
    this.setData({
      categoryResultId: id,
      'storeProduct.classifyId': id,
      categoryName: name
    })
  },
  useStartTimeChange(e){
    this.setData({
      'storeProduct.useStartTime':e.detail.value
    })
  },
  useEndTimeChange(e){
    this.setData({
      'storeProduct.useEndTime':e.detail.value
    })
  },
  //修改提前多久预约
  changeAppoinUnit(e){
    this.setData({
      'storeProduct.appoinNum':e.detail.value
    })
  },
  //增加提前多久预约
  plusAppoinUnit() {
    let val = this.data.storeProduct.appoinNum
    this.setData({
      'storeProduct.appoinNum':++val
    })
  },
  //减少提前多久预约
  deleteAppoinUnit() {
    let val = this.data.storeProduct.appoinNum
    if(val <= 0) {
      return
    }
    this.setData({
      'storeProduct.appoinNum':--val
    })
  },
  //更改商铺名
  changeProductName(e){
    this.setData({'storeProduct.productName':e.detail.value})
  },
  //选择分类
  bindClassifyChange(e){
    let item = this.data.classifyList[e.detail.value]
    this.setData({
      classifyIndex: e.detail.value,
      'storeProduct.classifyId':item.id
    })
  },
  //上传主图
  uploadImg: function (e) {
    var that = this;
    wx.showActionSheet({
     itemList: ['相册', '相机'],
     itemColor: "#40ba67",
     success: function (res) {
      if (!res.cancel) {
       if (res.tapIndex == 0) {
        that.chooseWxImageShop('album')
       } else if (res.tapIndex == 1) {
        that.chooseWxImageShop('camera')
       }
      }
     }
    })
   },
   chooseWxImageShop: function (type) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: [type],
      success: function (res) {
        //门店形象照
        API_Upload.upload(res.tempFilePaths[0],res=>{
          const {url} = JSON.parse(res.data)
            that.setData({'storeProduct.productImage':url})
      },res=>{
          wx.showToast({
              title:'上传失败',
              icon:'none'
          })
      })
      }
    })
  },
  //更改团单售价
  changePrice(e){
    this.setData({'storeProduct.price':e.detail.value})
  },
  //更改虚拟销量
  changeFictiNum(e){
    if(e.detail.value*1 > 99){
      wx.showToast({
        title: '最大数量不得超出99',
        icon:'none',
        duration:1500
      })
    }
    this.setData({'storeProduct.fictiNum':e.detail.value})
  },
  //虚拟次数
  changeWriteOffNum(e) {
    this.setData({'storeProduct.writeOffNum':e.detail.value})
  },
  //会员售价
  changeVipPrice(e) {
    this.setData({'storeProduct.vipPrice':e.detail.value})
  },
  //是否热卖
  hotStateChange:function(e){
    let item = this.data.YNArray[e.detail.value]
    this.setData({
      hotStateIndex:e.detail.value,
      'storeProduct.hotState':item.key
    });
  },
   //是否新人专享
  newUserStateChange:function(e){
    let item = this.data.YNArray[e.detail.value]
    this.setData({
      newUserStateIndex:e.detail.value,
      'storeProduct.isVip':item.key
    });
  },
  //是否固定有效期
  fixedTimeStateIndexChange:function(e){
    let item = this.data.YNArray[e.detail.value]
    this.setData({
      fixedTimeStateIndex:e.detail.value,
      'storeProduct.fixedTimeState':item.key
    });
  },
  //是否固定有效期radio
  radioTimeChange(e) {
    this.setData({
      'storeProduct.fixedTimeState': e.detail.value
    })
  },
  //多久预约的值
  appoinUnitIndexChange:function(e){
    let item = this.data.unitArray[e.detail.value]
    this.setData({
      appoinUnitIndex:e.detail.value,
      'storeProduct.appoinUnit':item.value
    });
  },
   //更改团单售价
   changeValidDay(e){
    this.setData({
        'storeProduct.validDay':e.detail.value,
      })
  },
  //商家服务选择
  seviceSelect(e){
    let data = JSON.stringify(e.detail.data)
    this.setData({'storeProduct.service':data})
  },
  //适用人群选择
  peopleSelect(e){
    let data = JSON.stringify(e.detail)
    this.setData({'storeProduct.peopleRight':data})
  },
  //适用人数
  changePeopleNum(e) {
    const val = e.detail.value
    this.setData({
      'storeProduct.peopleNum': Number(val)
    })
  },
  //增加适用人数
  plusPeopleNum() {
    let val = this.data.storeProduct.peopleNum
    this.setData({
      'storeProduct.peopleNum': ++val
    })
  },
  //减少适用人数
  deletePeopleNum() {
    let val = this.data.storeProduct.peopleNum
    if(val <= 0) {
      return
    }
    this.setData({
      'storeProduct.peopleNum': --val
    })
  },
  //是否会员专享
  radioChange(e) {
    console.log(e)
    this.setData({
      'storeProduct.isVip': e.detail.value
    })
  },
  saveAtt(e){
    let that = this
    that.setData({showCommit:!that.data.showCommit})
    let product = that.data.storeProduct
    console.log(product)
    product.price = product.price + ''
    product.fictiNum = product.fictiNum + ''
    // let arr = []
    // if(product.peopleRight.trim()){
    //   arr = JSON.parse(product.peopleRight)
    // }
    if(!product.productName.trim()){
      wx.showToast({title:'请输入团单名',duration:1500,icon:'none'})
      that.setData({showCommit:!that.data.showCommit})
      return
    }else if(!product.productImage.trim()){
      wx.showToast({title:'请上传图片',duration:1500,icon:'none'})
      that.setData({showCommit:!that.data.showCommit})
      return
    }else if(!product.price.trim()){
      wx.showToast({title:'团购价格不得为空',duration:1500,icon:'none'})
      that.setData({showCommit:!that.data.showCommit})
      return
    }else if(!product.fictiNum.trim()){
      wx.showToast({title:'请输入虚拟销量',duration:1500,icon:'none'})
      that.setData({showCommit:!that.data.showCommit})
      return
    }else if(product.fictiNum*1 > 99){
      wx.showToast({title:'虚拟销量不得大过99',duration:1500,icon:'none'})
      that.setData({showCommit:!that.data.showCommit})
      return
    }
    else if(!product.appoinNum){
      wx.showToast({title:'请输入提前多久预约',duration:1500,icon:'none'})
      that.setData({showCommit:!that.data.showCommit})
      return
    }else if(!product.peopleNum || product.peopleNum < 1){
      wx.showToast({title:'请输入适用人数',duration:1500,icon:'none'})
      that.setData({showCommit:!that.data.showCommit})
      return
    }else if(product.peopleRight.length <= 4){
      wx.showToast({title:'请选择适用人群',duration:1500,icon:'none'})
      that.setData({showCommit:!that.data.showCommit})
      return
    }else if(product.fixedTimeState == 'Y'){
      product.validDay = product.validDay + ''
      if(!product.validDay.trim()){
      wx.showToast({title:'请输入有效期天数',duration:1500,icon:'none'})
      that.setData({showCommit:!that.data.showCommit})
      return
      }
    }
    that.choiceAttGuige.save()
  },

  getAtt(e){
    this.setData({'storeProduct.infoId':e.detail.data.id})
    // 调用团单项目组件
    this.choiceProductAttr.callback()

  },
  //团单回调
  productAttr(e){
    let that = this
    if(!e.detail.exist){
      wx.showToast({
        title: '至少添加一个团单项目',
        duration:1500,
        icon:'none'
      })
      that.setData({showCommit:!that.data.showCommit})
      return
    }
    let productList = JSON.parse(e.detail.data)
    var totalPrice = 0
    for(var i = 0; i < productList.length; i++){
      let product = productList[i]
      // debugger
      if('mainAttr' == product.type){
        for(var j = 0; j < product.value.length; j++){
          let value =product.value[j]
          if(!value.productName.trim() && !value.price.trim()){
            wx.showToast({
              title: '请填写全含项目内项目名/价格',
              duration:1500,
              icon:'none'
            })
            that.setData({showCommit:!that.data.showCommit})
            return
          }
          totalPrice = totalPrice + value.price  * 1  
        }
      }else if('multipleAttr' == product.type){
        var itemPriceArr = []
        for(var j = 0; j < product.value.length; j++){
          let value =product.value[j]
          if(!value.productName.trim() && !value.price.trim()){
            wx.showToast({
              title: '请填写多选项目内项目名/价格',
              duration:1500,
              icon:'none'
            })
            that.setData({showCommit:!that.data.showCommit})
            return
          }
          itemPriceArr.push(value.price*1)
        }
        var arr =  itemPriceArr.sort(function(a, b){return b - a});
        for(var u = 0; u < product.selectIndex*1+1; u++){
          totalPrice = totalPrice + arr[u] * 1
        }
        // var itemPrice = Math.max(...itemPriceArr)
        // totalPrice = totalPrice + itemPrice * 1
        itemPriceArr = []
      }
    }

    let product = that.data.storeProduct
    product.itemDetail = e.detail.data
    
    product.storePrice = totalPrice
    console.log(product);
    if(product.id){
      API_Product.update(product).then(res=>{
        var pages = getCurrentPages();
        var beforePage = pages[pages.length - 2];
        wx.navigateBack({
          delta: 0,
          success(){
            beforePage.flush()
          }
        })  
      })
    }else{
      API_Product.create(product).then(res =>{
        var pages = getCurrentPages();
        var beforePage = pages[pages.length - 2];
        wx.navigateBack({
          delta: 0,
          success(){
            beforePage.flush()
          }
        })
      })
    }
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.type == 1){
      this.setData({
        title:'新增商品'
      })
    }
    if(options.copy){
      this.setData({
        isCopy:'copy'
      })
    }
    //适用人群
    this.choicePeopleGuige = this.selectComponent("#peopleArray")
    //商家服务
    // this.choiceServiceGuige = this.selectComponent("#serviceItem")
    //富文本
    this.choiceAttGuige = this.selectComponent("#richEditor")
    //团单组件
    this.choiceProductAttr = this.selectComponent("#productAttr")
    this.loadClassify(options.id)
  },
  //加载分类数据
  loadClassify(productId){
    API_Classify.getClassifySecond().then(res =>{
      if(!productId){
        const arr = []
        const list = res
        list.sort((a,b) => {
          return a.orderNum - b.orderNum
        }).reverse()
        // console.log(list)
        for(let i = list.length - 1; i >= 0; i--) {
          if(list[i].parentId == 0) {
            arr.push(list[i])
            list.splice(i,1)
          }
        }
        // list.forEach((item,index) => {
        //   if(item.parentId == 0) {
        //     arr.push(item)
        //   }
        //   list.splice(index,1)
        // })

        //这里只考虑二级，三级以上可做递归处理
        if(list.length) {
          list.forEach(item => {
            const obj = arr.find(i => {
              return i.id == item.parentId
            })
            if(obj) {
              //因为list是从大到小的，所以需要unshift往前添加
              if(obj.hasOwnProperty('children')) {
                  obj['children'].unshift(item)
                } else {
                  Object.defineProperty(obj,'children',{
                    value: []
                  })
                  // obj['children'] = []
                  obj['children'].unshift(item)
              }
            }
            
          })
        }
        //如果没children的话，给他添加一级分类当做二级分类
        arr.forEach(item => {
          if(!item.hasOwnProperty('children')) {
            item['children'] = []
            item['children'].push({
              id: item.id,
              classifyName: item.classifyName
            })
          }
        })
        const right = arr[0]['children'].length ?  arr[0]['children'] : []
        // console.log(arr)
        this.setData({
          classifyList:arr,
          categoryRight: right,
          // 'storeProduct.classifyId':res[0].id,
          'storeProduct.classifyId':arr[0]['children'] ? arr[0]['children'][0]['id'] : arr[0]['id'],
          categoryResultId: arr[0]['children'] ? arr[0]['children'][0]['id'] : arr[0]['id'],
          categoryName: arr[0]['children'] ? arr[0]['children'][0]['classifyName'] : arr[0]['classifyName']
        })
        let r = {
          key:'jy_people_right',
          title:'选择适用人群'
        }
        let e = {
          key:'jy_service_item',
          title:'选择商家服务',
          selectAll:true
        }
        this.choicePeopleGuige.loadDic(r)
        // this.choiceServiceGuige.loadDic(e)
      }else{
        API_Product.get(productId).then(ref =>{
          if(ref.success){
            let r = {
              key:'jy_people_right',
              title:'选择适用人群',
              selected:ref.product.peopleRight
            }
            let e = {
              key:'jy_service_item',
              title:'选择商家服务',
              selected:ref.product.service
            }
            this.choicePeopleGuige.loadDic(r)
            // this.choiceServiceGuige.loadDic(e)
            this.setData({
              storeProduct:ref.product
            })
            if(this.data.isCopy == 'copy'){
              this.setData({
                'storeProduct.id':null,
                title:'新增商品'
              })
            }
            //处理是否会员专享
            let vipArr = this.data.vipArr
            vipArr.forEach(item => {
              if(item.value == ref.product.isVip) {
                item['checked'] = true
              } else {
                item['checked'] = false
              }
            })
            this.setData({
              vipArr
            })
            //处理固定有效期
            let timeArr = this.data.timeArr
            timeArr.forEach(item => {
              if(item.value == ref.product.fixedTimeState) {
                item['checked'] = true
              } else {
                item['checked'] = false
              }
            })

            this.setData({
              timeArr
            })
            //加载富文本编辑器
              this.choiceAttGuige.init('',ref.product.infoId)
              //加载
              this.choiceProductAttr.loadAttr(ref.product.itemDetail)


        //注意注意，这里是分类处理
              // for(var i = 0; i < res.length; i++){
              //   if(res[i].id == ref.product.classifyId){
              //     this.setData({
              //       classifyList:res,
              //       classifyIndex:i
              //     })
              //     break
              //   }
              // }
            
              // for(var i = 0; i < res.length; i++){
              //   if(ref.product.classifyId == res[i].id){
              //     this.setData({
              //       classifyIndex:i
              //     })
              //     break
              //   }
              // }
              const arr = []
              let className = ''
        const list = res
        list.sort((a,b) => {
          return a.orderNum - b.orderNum
        }).reverse()
        for(let i = 0; i < list.length; i++) {
          if(list[i].id == ref.product.classifyId) {
            className = list[i]['classifyName']
          }
        }
        for(let i = list.length - 1; i >= 0; i--) {
          if(list[i].parentId == 0) {
            arr.push(list[i])
            list.splice(i,1)
          }
        }
        // list.forEach((item,index) => {
        //   if(item.parentId == 0) {
        //     arr.push(item)
        //   }
        //   list.splice(index,1)
        // })
        console.log(list)
        //这里只考虑二级，三级以上可做递归处理
        if(list.length) {
          list.forEach(item => {
            const obj = arr.find(i => {
              return i.id == item.parentId
            })
            if(obj) {
              if(obj.hasOwnProperty('children')) {
                  obj['children'].unshift(item)
                } else {
                  Object.defineProperty(obj,'children',{
                    value: []
                  })
                  // obj['children'] = []
                  obj['children'].unshift(item)
              }
            }
            
          })
        }
        //如果没children的话，给他添加一级分类当做二级分类
        arr.forEach(item => {
          if(!item.hasOwnProperty('children')) {
            item['children'] = []
            item['children'].push({
              id: item.id,
              classifyName: item.classifyName
            })
          }
        })
        console.log(arr)
        const idx = this.findParentObj(ref.product.classifyId,arr) 
        const right = arr[idx]['children'].length ?  arr[idx]['children'] : []
        this.setData({
          categoryLeft: idx,
          classifyList:arr,
          categoryRight: right,
          // 'storeProduct.classifyId':res[0].id,
          'storeProduct.classifyId':ref.product.classifyId,
          categoryResultId: ref.product.classifyId,
          categoryName: className
        })

              //分类处理end

              for(var i = 0; i < this.data.unitArray.length; i++){
                if(ref.product.appoinUnit == this.data.unitArray[i].value){
                  this.setData({
                    appoinUnitIndex:i
                  })
                  break
                }
              }
              for(var i = 0; i <  this.data.YNArray.length; i++){
                if(ref.product.hotState ==this.data.YNArray[i].key){
                  this.setData({
                    hotStateIndex:i
                  })
                }
                if(ref.product.isVip ==this.data.YNArray[i].key){
                  this.setData({
                    newUserStateIndex:i
                  })
                }
                if(ref.product.fixedTimeState == this.data.YNArray[i].key){
                  this.setData({
                    fixedTimeStateIndex:i
                  })
                }
              }
            }
          })
      }
    })
  },
  findParentObj(id,arr) {
    let inx = 0
    arr.forEach((item,index) => {
      if(item.id == id) {
        inx = index
      } else {
        if(item.hasOwnProperty('children')) {
          const childIndex = this.findParentObj(id,item['children'])
          if(childIndex) {
            inx = index
          }
        }
      }
    })
    return inx
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

 
})
